package net.zdsoft.wpchat.support.dao.impl;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import net.zdsoft.keel.jdbc.JdbcBasicDao;
import net.zdsoft.keel.util.Validators;
import net.zdsoft.wpchat.support.dao.SqlTaskDao;
import net.zdsoft.wpchat.support.entity.ResultPack;

import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

/**
 * 语法执行dao实现
 *
 * @author xuan
 */
@Repository
public class SqlTaskDaoImpl extends JdbcBasicDao implements SqlTaskDao {

    @Override
    public ResultPack executeQuery(String sql) {
        final ResultPack resultPack = new ResultPack();
        return getJdbcTemplate().query(sql, new ResultSetExtractor<ResultPack>() {
            @Override
            public ResultPack extractData(ResultSet rs) throws SQLException {
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                String[] columnNames = new String[columnCount];
                for (int i = 0; i < columnCount; i++) {
                    String columnName = rsmd.getColumnLabel(i + 1);
                    if (Validators.isEmpty(columnName)) {
                        columnName = String.valueOf(i + 1);
                    }
                    columnNames[i] = columnName;
                }
                resultPack.setColumnNames(columnNames);
                while (rs.next()) {
                    String[] record = new String[columnCount];

                    for (int i = 0; i < columnCount; i++) {
                        record[i] = rs.getString(i + 1);
                    }
                    resultPack.addRecord(record);
                }
                return resultPack;
            }
        });
    }

    @Override
    public int executeUpdate(String sql) {
        return update(sql);
    }

}
